﻿using System;
using System.Collections.Generic;
using System.Globalization;
using CustomerContactSystem.Core.Infrastructure.Utility;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries {
    public partial class Edit : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];

            GetClassifications();
            GetSources();
            GetReps();
            GetDepartments();
            GetEnquiry();
        }

        private void GetClassifications() {
            var enquiryClassifications = EnquiryClassificationRepository.QueryOver().OrderBy(c => c.Classification).Asc.List();
            BindDropDownList(Classifications, enquiryClassifications, "Classification", "Id", "--Select--", "0");
        }

        private void GetSources() {
            var enquirySources = EnquirySourceRepository.QueryOver().OrderBy(s => s.SourceName).Asc.List();
            BindDropDownList(Sources, enquirySources, "SourceName", "Id", "--Select--", "0");
        }

        private void GetReps() {
            var reps = RepRepository.QueryOver().Where(r => r.IsActive).OrderBy(r => r.FirstName).Asc.ThenBy(r => r.SecondName).Asc.List();
            BindDropDownList(Reps, reps, "FullName", "Id", "--N/A--", "0");
        }

        private void GetDepartments() {
            var departments = DepartmentRepository.QueryOver().OrderBy(d => d.DepartmentName).Asc.List();
            BindDropDownList(Departments, departments, "DepartmentName", "Id", "--Select--", "0");
        }

        private void GetEnquiry() {
            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null) {
                return;
            }

            FixYourStreetId.Text = enquiry.FixYourStreetId.ToString(CultureInfo.InvariantCulture);
            SetDropDownListIndexFromValue(Classifications, enquiry.Classification.Id.ToString(CultureInfo.InvariantCulture));
            SetDropDownListIndexFromValue(Departments, enquiry.Category.Department.Id.ToString(CultureInfo.InvariantCulture));
            SetDropDownListIndexFromValue(Sources, enquiry.Source.Id.ToString(CultureInfo.InvariantCulture));
            IsMediaEnquiry.Checked = enquiry.IsMediaEnquiry;
            IsConfidential.Checked = enquiry.IsConfidential;
            SetDropDownListIndexFromValue(Reps, enquiry.Rep != null ? enquiry.Rep.Id.ToString(CultureInfo.InvariantCulture) : "0");
            EnquiryDetail.Text = enquiry.EnquiryDetail.Replace("<br />", "/n");
            Deadline.Text = enquiry.Deadline.ToString("dd/MM/yyyy HH:mm");

            if (enquiry.FirstReferral != null) {
                return;
            }

            FixYourStreetIdCaption.Visible = false;
            FixYourStreetId.Visible = false;
            DeadlineCaption.Visible = false;
            Deadline.Visible = false;
            FixYourStreetWarning.Visible = false;
        }

        protected void UpdateEnquiryClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null) {
                UpdateEnquiryResultMessage.Text = "Error Enquiry not found!";
                return;
            }

            var changes = GetChanges(enquiry);
            int fysId;
            DateTime deadlineDate;

            int.TryParse(FixYourStreetId.Text, out fysId);
            DateTime.TryParse(Deadline.Text, out deadlineDate);

            if (enquiry.FirstReferral != null) {
                enquiry.FixYourStreetId = int.Parse(FixYourStreetId.Text);
                enquiry.Deadline = deadlineDate;
            }

            enquiry.Classification = EnquiryClassificationRepository.LoadReference(int.Parse(Classifications.SelectedItem.Value));
            enquiry.Source = EnquirySourceRepository.LoadReference(int.Parse(Sources.SelectedItem.Value));
            enquiry.IsMediaEnquiry = IsMediaEnquiry.Checked;
            enquiry.IsConfidential = IsConfidential.Checked;
            enquiry.Rep = Reps.SelectedIndex == 0 ? null : RepRepository.LoadReference(int.Parse(Reps.SelectedItem.Value));
            enquiry.EnquiryDetail = EnquiryDetail.Text.HtmlStripped().Replace("/n", "<br />");

            if (!IsValidObject(enquiry, UpdateEnquiryResultMessage)) {
                return;
            }

            foreach (var enquiryHistory in changes) {
                enquiry.AddHistory(enquiryHistory.EventDate, enquiryHistory.EventDetail);
            }

            EnquiryRepository.Update(enquiry);

            if (enquiry.Category.Department.Id.ToString(CultureInfo.InvariantCulture) != Departments.SelectedItem.Value) {
                Response.Redirect("~/Enquiries/EditNewDepartment.aspx?id=" + enquiry.Id + "&dept=" +
                                  Departments.SelectedItem.Value);
            }
            else {
                Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
            }
        }

        private IEnumerable<EnquiryHistory> GetChanges(Enquiry enquiry) {
            var changedDate = DateTime.Now;
            var changes = new List<EnquiryHistory>();

            if (enquiry.FirstReferral != null) {
                if (enquiry.FixYourStreetId.ToString(CultureInfo.InvariantCulture) != FixYourStreetId.Text.Trim()) {
                    changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            "Fix Your Street Id changed from " + enquiry.FixYourStreetId + " to " + FixYourStreetId.Text +
                            " by " + LoggedUser.DisplayName
                    });
                }

                if (enquiry.Deadline.ToString("dd/MM/yyyy HH:mm") != Deadline.Text.Trim()) {
                    changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            "Deadline changed from " + enquiry.Deadline.ToString("dd/MM/yyyy HH:mm") + " to " +
                            Deadline.Text + " by " + LoggedUser.DisplayName
                    });
                } 
            }

            if (enquiry.Classification.Id.ToString(CultureInfo.InvariantCulture) != Classifications.SelectedItem.Value) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            "Classification changed from " + enquiry.Classification.Classification + " to " +
                            Classifications.SelectedItem.Text + " by " + LoggedUser.DisplayName
                    });
            }

            if (enquiry.Source.Id.ToString(CultureInfo.InvariantCulture) != Sources.SelectedItem.Value) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            "Source changed from " + enquiry.Source.SourceName + " to " + Sources.SelectedItem.Text +
                            " by " + LoggedUser.DisplayName
                    });
            }

            if (enquiry.IsMediaEnquiry != IsMediaEnquiry.Checked) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            IsMediaEnquiry.Checked
                                ? "Set as Media Enquiry by " + LoggedUser.DisplayName
                                : "Set as not Media Enquiry by " + LoggedUser.DisplayName
                    });
            }

            if (enquiry.IsConfidential != IsConfidential.Checked) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            IsConfidential.Checked
                                ? "Set as Confidential by " + LoggedUser.DisplayName
                                : "Set as not Confidential by " + LoggedUser.DisplayName
                    });
            }

            if (enquiry.Rep == null && Reps.SelectedIndex > 0) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            "Rep set on enquiry to " + Reps.SelectedItem.Text + " by " + LoggedUser.DisplayName
                    });
            }

            if (enquiry.Rep != null && Reps.SelectedIndex == 0) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail = "Rep " + enquiry.Rep.FullName + " removed by " + LoggedUser.DisplayName
                    });
            }

            if (enquiry.Rep != null && enquiry.Rep.Id.ToString(CultureInfo.InvariantCulture) != Reps.SelectedItem.Value) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail =
                            "Rep changed from " + enquiry.Rep.FullName + " to " + Reps.SelectedItem.Text + " by " +
                            LoggedUser.DisplayName
                    });
            }

            if (enquiry.EnquiryDetail.Replace("<br />", "/n") != EnquiryDetail.Text.Trim()) {
                changes.Add(new EnquiryHistory
                    {
                        EventDate = changedDate,
                        EventDetail = "Enquiry detail updated by " + LoggedUser.DisplayName
                    });
            }   
         
            return changes;
        }
    }
}